Adding data to your Svelte component

Posted on 2023-01-28 by

henrikvilhelmberglund
<script>
  
</script>

Script tags allow you to add logic and data in your components.

For example we can define a variable in the script tag and then use it in the markup by putting it inside curly brackets .

Hello Reader

<script>
  let name = "Reader";
</script>

<p>Hello {name}</p>

Note that these variables need to be defined in the top level (not in functions).

We can also use variables in HTML tags to have dynamic attributes .

a svelte logo
<script>
	let url = "https://svelte.dev/images/svelte-android-chrome-192.png";
</script>

<img src={url} alt="a svelte logo" />

If the variable and attribute have the same name we can use a shorthand .

a svelte logo
<script>
	let src = "https://svelte.dev/images/svelte-android-chrome-192.png";
</script>

<img {src} alt="a svelte logo" />